﻿using MaxStoreErp.Core.BaseClasses;
using MaxStoreErp.Core.Commands;
using MaxStoreErp.Core.Exceptions;
using MaxStoreShop.Logic.ServicesContracts.Directories;
using Microsoft.Practices.Unity;

namespace MaxStoreShop.CoreModule.ChangePasswordDialog
{
    internal class ChangePasswordDialogPresenter :
        PresenterBase<ChangePasswordDialogView, ChangePasswordDialogViewModel>
    {
        [Dependency]
        public IUserService UserService { get; set; }

        protected override void OnViewModelSet()
        {
            base.OnViewModelSet();
            ViewModel.CancelCommand = new RelayCommand(CancelChanging);
            ViewModel.EnterCommand = new RelayCommand(EnterNewPassword, CanEnterCommand);
            ViewModel.OnFieldChanged = () => ViewModel.ErrorText = string.Empty;
        }

        void EnterNewPassword()
        {
            if (string.CompareOrdinal(ViewModel.NewPassword, ViewModel.ReenteredNewPassword) != 0)
            {
                ClearFields();
                ViewModel.ErrorText = "Введеный новый пароль не совпадает с повторением!";
                return;
            }

            if (string.CompareOrdinal(ViewModel.SelectedUser.SecretCode, ViewModel.OldPassword) != 0)
            {
                ClearFields();
                ViewModel.ErrorText = "Вы указали неверный старый пароль!";
                return;
            }

            ViewModel.SelectedUser.SecretCode = ViewModel.NewPassword;
            UserService.SaveUser(ViewModel.SelectedUser);
            UserMessage.CloseCustomDialogAsync();
        }

        void ClearFields()
        {
            ViewModel.OldPassword = string.Empty;
            ViewModel.NewPassword = string.Empty;
            ViewModel.ReenteredNewPassword = string.Empty;
            View.OldPasswordBox.Focus();
        }

        void CancelChanging()
        {
            UserMessage.CloseCustomDialogAsync();
        }

        bool CanEnterCommand()
        {
            return !string.IsNullOrWhiteSpace(ViewModel.OldPassword) &&
                   !string.IsNullOrWhiteSpace(ViewModel.NewPassword) &&
                   !string.IsNullOrWhiteSpace(ViewModel.ReenteredNewPassword);
        }

        protected override void OnDataLoading()
        {
            base.OnDataLoading();
            if (ViewModel.SelectedUser ==null)
                throw new ErpRuntimeException("Для изменения пользователя необходимо указать пользователя!");
        }
    }
}
